/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package JPA;

import DAO.InformeDAO;
import domain.Entity.EntityInforme;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.UserTransaction;

/**
 *
 * @author jorge
 */
public class JPAInformeDAO implements InformeDAO {

    public void anadirInforme(EntityInforme ei) {
        try {
            Context ctx = new InitialContext();
            UserTransaction utx = (UserTransaction) ctx.lookup("java:comp/env/UserTransaction");


        try {
            utx.begin();
            EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/baronPU");
            em.persist(ei);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception exe) {
                System.out.println("Rollback failed: "+exe.getMessage());
                }
              }
             } catch (NamingException ex) {
            Logger.getLogger(JPAInformeDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public List listarInformes(long dni) {
        List resultado = new ArrayList();
       try {
            
            Context ctx = new InitialContext();
            EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/baronPU");
            Query q = em.createQuery("SELECT i FROM EntityInforme i WHERE i.eu.dni = :dni");
            q = q.setParameter("dni", dni);
            resultado = q.getResultList();
             } catch (NamingException ex) {
            Logger.getLogger(JPAInformeDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
    return resultado;
    }

    public void borrarInforme(long idInforme) {
         EntityInforme ei = new EntityInforme();
        try {
            Context ctx = new InitialContext();
            UserTransaction utx = (UserTransaction) ctx.lookup("java:comp/env/UserTransaction");


        try {
            utx.begin();
            EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/baronPU");
            ei = em.find(domain.Entity.EntityInforme.class, idInforme);
            em.remove(ei);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception exe) {
                System.out.println("Rollback failed: "+exe.getMessage());
                }
              }
             } catch (NamingException ex) {
            Logger.getLogger(JPAProyectoDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}


